# -*- coding: UTF-8 -*-


# 定时任务


# 定时任务的模块
import schedule
import time
from service import spider
from domain import product
from domain import price_history
from dao import productDao
from dao import productHistoryDao
from util import Mytime


# 设置定时任务,每天定时爬去urls页面的价格存储到数据库中
def set_task(product_urls):
    price = None
    price_srouce = None

    for pro in product_urls:

        # 获取url的平台类型：天猫还是京东
        price_srouce = spider.decide_url_type(pro['url'])
        # 获取价格
        price = spider.get_price_from_url(pro['url'])

        if price and price_srouce:
            p = productDao.get_by_name(pro['name'])
            if not p:
                p = product.product()
                p = init_price_prop(p, pro['name'], price, price_srouce, pro['url'])
                productDao.save(p)
                history = create_history_by_product(p)
                productHistoryDao.save(history)
            else:
                # 判断价格是否变动
                change = decide_price_change(price, price_srouce, p)
                if change:
                    print("价格有变动，开始更新价格,name:"+p['name'])
                    p = set_price_prop(p, price, price_srouce, pro['url'])
                    productDao.update_product(p)
                    product_history_update_price_record(p['_id'], price_srouce, price)
    print("执行结束！")


def decide_price_change(new_price, price_source, product):
    old_price = None
    if new_price and price_source and product:
        if price_source == 1:
            old_price = product['myprice']['jd']['price']
        elif price_source == 2:
            old_price = product['myprice']['tm']['price']
        if not old_price:
            if old_price != new_price:
                return True
            return False
    return None


def create_history_by_product(product):
    history = price_history.history()
    # history = {}
    # product 现在是object类型
    product = productDao.get_by_name(product.name)
    # product 现在是dict类型
    history.product_id = product['_id']
    history.name = product['name']
    tm_record = {}
    jd_record = {}
    # 判断'tm'是否在字典中
    if 'tm' in product['myprice']:
        tm_record['price'] = product['myprice']['tm']['price']
        tm_record['created'] = product['myprice']['tm']['created']
        history.tm_price_record.append(tm_record)
    # 判断'jd'是否在字典中
    if 'jd' in product['myprice']:
        jd_record['price'] = product['myprice']['jd']['price']
        jd_record['created'] = product['myprice']['jd']['created']
        history.jd_price_record.append(jd_record)
    return history


def product_history_update_price_record(product_id, price_source, price):
    history = productHistoryDao.find_by_product_id(product_id)
    if price_source == 1:
        jd_record = {}
        jd_record['price'] = price
        jd_record['created'] = Mytime.get_local_time()
        history['jd_price_record'].append(jd_record)
    elif price_source == 2:
        tm_record = {}
        tm_record['price'] = price
        tm_record['created'] = Mytime.get_local_time()
        history['tm_price_record'].append(tm_record)
    productHistoryDao.save(history)


# 设置产品的属性
def set_price_prop(product, price, price_source, url):
    if price_source == 1:
        product['myprice']['jd'] = {'name': 'jd', 'price': price, 'created': Mytime.get_local_time(), 'url': url}
    elif price_source == 2:
        product['myprice']['tm'] = {'name': 'tm', 'price': price, 'created': Mytime.get_local_time(), 'url': url}
    return product


def init_price_prop(product, name, price, price_source, url):
    product.name = name
    if price_source == 1:
        product.myprice['jd'] = {'name': 'jd', 'price': price, 'created': Mytime.get_local_time(), 'url': url}
    elif price_source == 2:
        product.myprice['tm'] = {'name': 'tm', 'price': price, 'created': Mytime.get_local_time(), 'url': url}
    return product


def job():
    # triton700  在天猫和jd的价格
    pro1 = {'name': 'triton700', 'url': 'https://item.jd.com/4719455.html'}
    # rog gm501在京东的价格
    pro2 = {'name': 'rog gm501', 'url': 'https://item.jd.com/6906538.html'}
    # thinkpad t470p
    pro3 = {'name': 'thinkpad t470p 2k', 'url': 'https://item.jd.com/20819451436.html'}
    # thinkpad p51
    pro4 = {'name': 'thinkpad p51 4k', 'url': 'https://item.jd.hk/26402753187.html'}
    pro5 = {'name': 'thinkpad p51 4k', 'url': 'https://detail.tmall.com/item.htm?spm=a1z10.5-b.w4011-16763141439.55.21df2bad1HVKCi&id=561029820393&rn=9b02580c7e442c7df2ceb573563a9973&abbucket=18&skuId=3512909096494'}

    products = []
    products.append(pro1)
    products.append(pro2)
    products.append(pro3)
    products.append(pro4)
    products.append(pro5)
    set_task(products)





# 测试定时获取价格
if __name__ == "__main__":
    # product=productDao.get_by_name('triton700')
    # id=product['_id']
    # print(product)
    # schedule.every(1).minutes.do(job)
    job()
    # while True:
        # schedule.run_pending()
        # time.sleep(1)
    # for i in range(1,5):
    # while True:
